<template>
  <div class="app-container">
    <el-card>
      <el-form :model="queryParams" ref="queryRef" :inline="false" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="入库状态" prop="receiptOrderStatus">
              <el-radio-group v-model="queryParams.orderStatus" @change="handleQuery">
                <el-radio-button label="all">
                  全部
                </el-radio-button>
                <el-radio-button v-for="item in wms_receipt_status" :key="item.value" :label="item.value">
                  {{ item.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="入库类型" prop="optType">
              <el-radio-group v-model="queryParams.optType" @change="handleQuery">
                <el-radio-button :key="-1" :label="-1">
                  全部
                </el-radio-button>
                <el-radio-button v-for="item in wms_receipt_type" :key="item.value" :label="item.value">
                  {{ item.label }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="入库单号" prop="orderNo">
              <el-input v-model="queryParams.orderNo" placeholder="请输入入库单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="往来单位" prop="supplierName">
              <el-input v-model="queryParams.supplierName" placeholder="请输入往来单位名称" clearable
                @keyup.enter="handleQuery" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制单时间">
              <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" value-format="yyyy-MM-dd" @change="handleDateChange" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="mt20">
      <!-- 操作说明提示 -->
      <el-alert title="业务流程说明" type="info" :closable="false" class="mb10">
        <template #default>
          <div style="font-size: 13px; line-height: 22px;">
            <p>📋 <strong>完整流程：</strong>创建收货单 → 确认到货 → 验收管理 → 上架管理 → 签字完成</p>
            <p>🔄 <strong>状态流转：</strong>
              <el-tag size="mini" type="info">未收货</el-tag> →
              <el-tag size="mini" type="warning">待验收</el-tag> →
              <el-tag size="mini" type="primary">待上架</el-tag> →
              <el-tag size="mini" type="success">已签字</el-tag>
            </p>
            <p>⚠️ <strong>异常处理：</strong>验收不通过或上架异常时，状态回滚至<el-tag size="mini" type="danger">异常</el-tag>状态</p>
          </div>
        </template>
      </el-alert>

      <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
        <el-col :span="6"><span style="font-size: large">入库单据</span></el-col>
        <el-col :span="1.5">
          <el-button type="primary" @click="handleAdd" v-hasPermi="['wms:receive:add']">新增收货单
          </el-button>
        </el-col>
      </el-row>
      <el-table :data="headerList" border class="mt20" height="calc(100vh - 400px)" style="width: 100%">
        <!-- 单据明细 -->
        <el-table-column type="expand" width="40">
          <template #default="{ row }">
            <div style="padding: 0 50px 20px 50px">
              <el-row :gutter="10" class="mb8" type="flex" justify="space-between">
                <el-col :span="6"><span style="font-size: large">单据明细</span></el-col>
              </el-row>
              <!-- 现在直接使用 row.inDetailList 展示明细数据 -->
              <el-table :data="row.inDetailList || []" border>
                <el-table-column show-overflow-tooltip type="index" label="行号" align="center"
                  min-width="60"></el-table-column>
                <el-table-column show-overflow-tooltip prop="drugId" label="药品编码" align="center" min-width="120" />
                <el-table-column show-overflow-tooltip prop="drugName" label="药品名称" align="center" min-width="200" />
                <el-table-column show-overflow-tooltip prop="drugCd" label="生产厂家" align="center" min-width="150" />
                <el-table-column show-overflow-tooltip prop="drugPZWH" label="批准文号" align="center" min-width="150" />
                <el-table-column show-overflow-tooltip prop="drugGg" label="规格" align="center" min-width="100" />
                <el-table-column show-overflow-tooltip prop="drugDw" label="单位" align="center" min-width="80" />
                <el-table-column show-overflow-tooltip prop="drugNum" label="数量" align="center" min-width="100" />
                <!-- 暂时隐藏确认数量，收货前无此信息 -->

                <!--                <el-table-column show-overflow-tooltip prop="drugBatchNo" label="批号" align="center" min-width="120"/>-->
                <!-- <el-table-column show-overflow-tooltip prop="drugCheckNum" label="确认数量" align="center" min-width="100"/> -->
                <!--                <el-table-column show-overflow-tooltip prop="drugPd" label="生产日期" align="center" min-width="120"/>-->
                <!--                <el-table-column show-overflow-tooltip prop="drugExp" label="有效期" align="center" min-width="120"/>-->
              </el-table>
            </div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="billsId" label="单据号" align="center" width="180"></el-table-column>
        <el-table-column show-overflow-tooltip prop="billsTypeName" label="单据类型" align="center"
          width="150"></el-table-column>
        <el-table-column show-overflow-tooltip prop="billsCdName" label="往来单位" align="center"
          min-width="150"></el-table-column>
        <el-table-column show-overflow-tooltip prop="totalPackages" label="总件数" align="center"
          width="90"></el-table-column>
        <el-table-column show-overflow-tooltip prop="totalQuantity" label="总数量" align="center"
          width="90"></el-table-column>
        <el-table-column show-overflow-tooltip label="单据状态" align="center" width="150">
          <template #default="scope">
            <el-tag v-if="scope.row.billsState === '0'" type="info">未收货</el-tag>
            <el-tag v-else-if="scope.row.billsState === '1'" type="warning">待验收</el-tag>
            <el-tag v-else-if="scope.row.billsState === '2'" type="primary">待上架</el-tag>
            <el-tag v-else-if="scope.row.billsState === '3'" type="success">已签字</el-tag>
            <el-tag v-else-if="scope.row.billsState === '4'" type="danger">异常</el-tag>
            <el-tag v-else>未知状态</el-tag>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="creatorName" label="制单人" align="center"
          width="100"></el-table-column>
        <el-table-column show-overflow-tooltip prop="createTime" label="制单时间" align="center"
          width="160"></el-table-column>
        <!-- 暂时隐藏签字人、验收人、上架人，录入收货单时无此信息 -->
        <!-- <el-table-column show-overflow-tooltip prop="secondUser" label="签字人" align="center" min-width="100"></el-table-column> -->
        <!-- <el-table-column show-overflow-tooltip prop="acceptUserName" label="验收人" align="center" min-width="100"></el-table-column> -->
        <!-- <el-table-column show-overflow-tooltip prop="shelvingUserName" label="上架人" align="center" min-width="100"></el-table-column> -->
        <el-table-column label="操作" align="center" width="300" fixed="right">
          <template #default="scope">
            <!-- 状态为0-未收货时：可以修改、可以作废、可以确认到货 -->
            <el-button v-if="scope.row.billsState === '0'" type="primary" size="small"
              @click="handleReceived(scope.row)" v-hasPermi="['wms:receive:received']">确认收货</el-button>
            <el-button v-if="scope.row.billsState === '0'" type="primary" size="small"
              @click="rejection(scope.row)" v-hasPermi="['wms:receive:received']">拒收</el-button>
            <el-button v-if="scope.row.billsState === '0'" type="danger" size="small" @click="handleCancel(scope.row)"
              v-hasPermi="['wms:receive:cancel']">作废</el-button>

            <!-- 状态为1-已到货待验收时：等待验收 -->
            <span v-if="scope.row.billsState === '1'" class="status-text">等待验收</span>

            <!-- 状态为2-验收完成待上架时：等待上架 -->
            <span v-if="scope.row.billsState === '2'" class="status-text">等待上架</span>

            <!-- 状态为3-已签字时：流程完成 -->
            <span v-if="scope.row.billsState === '3'" class="status-text success">流程完成</span>

            <!-- 状态为4-异常时：显示异常状态 -->
            <span v-if="scope.row.billsState === '4'" class="status-text error">异常状态</span>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="float: right; margin: 20px">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
          :page-sizes="[10, 50, 100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>

    <!-- 批次拆分对话框 - 表格编辑模式 -->
    <el-dialog title="确认收货 - 批次拆分" :visible.sync="batchDialogVisible" width="95%" :close-on-click-modal="false"
      top="3vh">
      <el-alert title="批次录入说明" type="info" :closable="false" style="margin-bottom: 20px;">
        <template #default>
          <p>📦 <strong>批次管理：</strong>可以直接在表格中编辑批号、生产日期、有效期和确认数量</p>
          <p>➕ <strong>新增批次：</strong>点击"添加批次"按钮可以添加同一商品的新批次（需填写不同批号）</p>
          <p>⚠️ <strong>数量校验：</strong>每个商品所有批次的确认数量总和必须等于原始数量</p>
        </template>
      </el-alert>

      <!-- 商品批次表格 -->
      <el-table :data="getBatchTableData()" border stripe max-height="600" :span-method="spanMethod">
        <el-table-column label="序号" type="index" width="60" align="center" />

        <!-- 商品信息列 -->
        <el-table-column label="商品编码" prop="drugId" width="120" align="center" show-overflow-tooltip />
        <el-table-column label="商品名称" prop="drugName" min-width="200" align="center" show-overflow-tooltip />
        <el-table-column label="规格" prop="drugGg" width="120" align="center" show-overflow-tooltip />
        <el-table-column label="单位" prop="drugDw" width="80" align="center" />
        <el-table-column label="生产厂家" prop="drugCd" min-width="150" align="center" show-overflow-tooltip />
        <!-- 批次序号 -->
        <el-table-column label="批次" width="80" align="center">
          <template slot-scope="scope">
            <el-tag size="small" :type="scope.row.batchSequence === 1 ? 'primary' : 'success'">
              批次{{ scope.row.batchSequence }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 批号 - 可编辑 -->
        <el-table-column label="批号" width="150" align="center">
          <template slot-scope="scope">
            <el-input v-model="scope.row.drugBatchNo" placeholder="请输入批号" size="small" clearable
              @blur="validateBatchNo(scope.row)" />
          </template>
        </el-table-column>

        <!-- 生产日期 - 可编辑 -->
        <el-table-column label="生产日期" width="160" align="center">
          <template slot-scope="scope">
            <el-date-picker v-model="scope.row.drugPd" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"
              size="small" style="width: 100%;" />
          </template>
        </el-table-column>

        <!-- 有效期 - 可编辑 -->
        <el-table-column label="有效期" width="160" align="center">
          <template slot-scope="scope">
            <el-date-picker v-model="scope.row.drugExp" type="date" placeholder="选择日期" value-format="yyyy-MM-dd"
              size="small" style="width: 100%;" />
          </template>
        </el-table-column>
        <!-- 数量 -->
        <el-table-column label="数量" prop="originalQty" width="100" align="center">
          <template slot-scope="scope">
            <el-tag type="info" size="small">{{ scope.row.originalQty }}</el-tag>
          </template>
        </el-table-column>
        <!-- 确认数量 - 可编辑 -->
        <el-table-column label="确认数量" width="120" align="center">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.drugCheckNum" :min="0.01" :max="999999" :precision="0" size="small"
              style="width: 100%;" @change="handleBatchQtyChange(scope.row)" />
          </template>
        </el-table-column>

        <!-- 已分配总数 -->
        <el-table-column label="已分配总数" width="110" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.totalAllocated == scope.row.originalQty ? 'success' : 'warning'" size="small">
              {{ Math.round(scope.row.totalAllocated) }}
            </el-tag>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="copyBatchRow(scope.row)"
              title="添加新批次">添加批次</el-button>
            <el-button v-if="canDelete(scope.row)" type="danger" icon="el-icon-delete" size="mini"
              @click="deleteBatchRow(scope.row)" title="删除此行" />
          </template>
        </el-table-column>
      </el-table>

      <!-- 底部汇总信息 -->
      <div style="margin-top: 20px; padding: 15px; background-color: #F5F7FA; border-radius: 4px;">
        <el-row :gutter="20">
          <el-col :span="8">
            <div style="font-size: 14px; color: #606266;">
              <i class="el-icon-goods" style="color: #409EFF;"></i>
              <strong>商品总数：</strong>{{ uniqueProductCount }} 个
            </div>
          </el-col>
          <el-col :span="8">
            <div style="font-size: 14px; color: #606266;">
              <i class="el-icon-document" style="color: #67C23A;"></i>
              <strong>批次总数：</strong>{{ getBatchTableData().length }} 个
            </div>
          </el-col>
          <el-col :span="8">
            <div style="font-size: 14px;" :style="{ color: allQtyMatched ? '#67C23A' : '#F56C6C' }">
              <i :class="allQtyMatched ? 'el-icon-success' : 'el-icon-warning'" />
              <strong>数量校验：</strong>{{ allQtyMatched ? '全部匹配 ✓' : '存在不匹配 ✗' }}
            </div>
          </el-col>
        </el-row>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="batchDialogVisible = false" size="medium">取消</el-button>
        <el-button :type="allQtyMatched ? 'primary' : 'warning'" @click="handleConfirmReceive" size="medium">
          {{ allQtyMatched ? '确认收货' : '部分收货' }}
        </el-button>
      </div>
    </el-dialog>
    <el-dialog title="拒收原因" @close="handleClose" :visible.sync="refuseVisible" width="60%"
      :close-on-click-modal="false">
      <el-form label-width="80px" :model="formList" ref="formRef" :rules="rules">
        <el-form-item label="拒收原因" prop="reason">
          <el-input type="textarea" placeholder="请输入拒收原因" v-model="formList.reason"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">确定</el-button>
        <el-button @click="handleClose">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  buyStoreList,
  receiveGoods,
  extractBills,
  pdaCompleted,
  signBills,
  cancelBills, rejectGoods,
} from '@/api/storage/buyStore'
  export default {
    data() {
      return {
        refuseVisible: false, //拒收弹框
        loading: false,
        total: 0,
        formList: {
          reason: ''
        },
        rules: {
          reason: [{
            required: true,
            message: '请输入拒收原因',
            trigger: 'blur'
          }]
        },
        pageSize: 10,
        pageNum: 1,
        dateRange: [],
        showDebugInfo: true, // 开发阶段显示调试信息
        queryParams: {
          orderNo: '',
          supplierName: '',
          orderStatus: "all",//收货管理
          optType: -1,//收货
          beginTime: null,
          endTime: null
        },
        wms_receipt_status: [{
            label: '未收货',
            value: '0'
          },
          {
            label: '已收货',
            value: '1'
          },
          {
            label: '异常',
            value: '4'
          }
        ],
        wms_receipt_type: [{
            label: '采购入库',
            value: 'PurchaseWareHouseIn'
          },
          {
            label: '生产入库',
            value: 'ProduceWareHouseIn'
          },
          {
            label: '退货入库',
            value: 'ReturnWareHouseIn'
          },
          {
            label: '调拨入库',
            value: 'AllocateWareHouseIn'
          },
          {
            label: '赠品入库',
            value: 'GiftHouseIn'
          },
          {
            label: '其他入库',
            value: 'OtherHouseIn'
          }
        ],
        headerList: [],

        // 批次拆分相关
        batchDialogVisible: false,
        currentBillId: '',
        currentBillDetails: [], // 当前单据的明细列表
      }
    },
    computed: {
      // 不同商品的数量
      uniqueProductCount() {
        return this.currentBillDetails.length
      },

      // 检查所有商品的批次数量是否都匹配
      allQtyMatched() {
        return this.currentBillDetails.every(detail => {
          // 使用确认数量 drugCheckNum 进行匹配检查
          const totalAllocated = detail.batches.reduce((sum, batch) =>
            sum + (parseFloat(batch.drugCheckNum || batch.drugNum) || 0), 0)
          return Math.abs(Math.round(totalAllocated) - Math.round(parseFloat(detail.drugNum))) < 0.01 // 允许0.01的浮点误差
        })
      }
    },
    created() {
      this.handleQuery();
    },
    methods: {
      //拒收原因关闭
      handleClose() {
        this.refuseVisible = false;
        this.$nextTick(() => {
          this.$refs.formRef.resetFields();
        })
      },
      //提交表单
      submit() {
        this.$refs.formRef.validate((valid) => {
          if (valid) {
            this.handleClose();
          } else {
            // 校验失败
            return false;
          }
        });
      },
      // 获取批次表格数据 - 直接返回源数据引用，避免深拷贝导致数据断裂
      getBatchTableData() {
        const result = []
        this.currentBillDetails.forEach((detail, detailIndex) => {
          if (detail.batches && detail.batches.length > 0) {
            detail.batches.forEach(batch => {
              // 计算该商品所有批次的总确认数量（使用 drugCheckNum）
              const totalAllocated = detail.batches.reduce((sum, b) =>
                sum + (parseFloat(b.drugCheckNum || b.drugNum) || 0), 0)

              // 直接在 batch 对象上添加辅助属性，不使用扩展运算符
              batch.originalQty = detail.drugNum // 原始数量
              batch.totalAllocated = totalAllocated // 已分配总数（确认数量）
              batch.detailIndex = detailIndex // 记录原始明细的索引

              result.push(batch)
            })
          }
        })
        return result
      },

      // 日期范围变化
      handleDateChange(dates) {
        if (dates && dates.length === 2) {
          this.queryParams.beginTime = dates[0]
          this.queryParams.endTime = dates[1]
        } else {
          this.queryParams.beginTime = null
          this.queryParams.endTime = null
        }
      },

      // 确认收货 - 打开批次拆分对话框
      handleReceived(row) {
        this.currentBillId = row.billsId;

        // 检查是否已经有保存的明细数据，如果有则使用保存的数据，否则初始化
        const details = (row.inDetailList || []).map(detail => {
          const batch = {
            drugId: detail.drugId || '',
            drugName: detail.drugName || '',
            drugGg: detail.drugGg || '',
            drugDw: detail.drugDw || '',
            drugCd: detail.drugCd || '',
            drugBatchNo: detail.drugBatchNo || '',
            drugPd: detail.drugPd || '',
            drugExp: detail.drugExp || '',
            drugNum: parseFloat(detail.drugNum) || 0,
            drugCheckNum: detail.drugCheckNum || 0,
          };

          return {
            ...detail,
            batches: [batch]
          };
        });

        this.currentBillDetails = details;
        this.batchDialogVisible = true;
      },

      // 表格合并单元格方法 - 合并相同商品的行
      spanMethod({
        row,
        column,
        rowIndex,
        columnIndex
      }) {
        // 需要合并的列：商品编码、商品名称、规格、单位、生产厂家、原始数量、已分配总数
        const mergeColumns = [1, 2, 3, 4, 5, 10, 12] // 列索引

        if (!mergeColumns.includes(columnIndex)) {
          return {
            rowspan: 1,
            colspan: 1
          }
        }

        // 找到相同商品的所有行
        const currentDrugId = row.drugId
        const allRows = this.getBatchTableData()

        // 计算当前商品在表格中的起始位置
        let firstIndex = -1
        let sameProductCount = 0

        for (let i = 0; i < allRows.length; i++) {
          if (allRows[i].drugId === currentDrugId) {
            if (firstIndex === -1) firstIndex = i
            sameProductCount++
          }
        }

        // 如果是该商品的第一行，合并所有同商品的行
        if (rowIndex === firstIndex) {
          return {
            rowspan: sameProductCount,
            colspan: 1
          }
        } else {
          // 其他行不显示
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      },

      // 复制批次行
      copyBatchRow(row) {
        const detail = this.currentBillDetails[row.detailIndex]
        const newBatchSequence = detail.batches.length + 1

        const newBatch = {
          drugId: row.drugId,
          drugName: row.drugName,
          drugGg: row.drugGg,
          drugDw: row.drugDw,
          drugCd: row.drugCd,
          drugBatchNo: '', // 批号清空，让用户填写新批次的批号
          drugPd: '', // 生产日期清空
          drugExp: '', // 有效期清空
          drugNum: row.drugNum, // 继承原始采购数量（用于多批次时的追踪）
          drugCheckNum: 0, // 新批次的确认数量初始为 0，由用户输入
          batchSequence: newBatchSequence,
          isOriginal: 0,
          parentDetailId: row.parentDetailId
        }

        detail.batches.push(newBatch)
        this.$message.success('已添加新批次，请填写批号、日期和确认数量')
      },

      // 删除批次行
      deleteBatchRow(row) {
        const detail = this.currentBillDetails[row.detailIndex]

        if (detail.batches.length <= 1) {
          this.$message.warning('至少保留一个批次')
          return
        }

        const batchIndex = detail.batches.findIndex(b => b.batchSequence === row.batchSequence)
        if (batchIndex > -1) {
          detail.batches.splice(batchIndex, 1)
          // 重新设置批次序号
          detail.batches.forEach((batch, index) => {
            batch.batchSequence = index + 1
          })
          this.$message.success('已删除批次')
        }
      },

      // 判断是否可以删除
      canDelete(row) {
        const detail = this.currentBillDetails[row.detailIndex]
        return detail.batches.length > 1
      },

      // 批号失焦验证
      validateBatchNo(row) {
        const batchNo = (row.drugBatchNo || '').trim();
        if (batchNo === '') {
          this.$message.warning('批号不能为空');
        }
      },

      // 批次数量变化时触发
      handleBatchQtyChange(row) {
        // 验证数量输入
        if (row.drugCheckNum < 0) {
          row.drugCheckNum = 0
          this.$message.warning('确认数量不能为负数')
          return
        }

        // 获取该商品的原始数量
        const detail = this.currentBillDetails[row.detailIndex]
        if (!detail) return

        // 计算该商品所有批次的总数量
        const totalAllocated = detail.batches.reduce((sum, b) =>
          sum + (parseFloat(b.drugCheckNum || 0) || 0), 0)

        // 如果超过原始数量，提示用户
        if (totalAllocated > parseFloat(detail.drugNum)) {
          this.$message.warning(`商品"${detail.drugName}"的分配数量不能超过原始数量${detail.drugNum}`)
        }

        // 强制更新视图
        this.$forceUpdate()
      },
      // 确认收货 - 处理批次拆分并提交
      handleConfirmReceive() {
        // 遍历当前单据明细
        for (let i = 0; i < this.currentBillDetails.length; i++) {
          const detail = this.currentBillDetails[i];

          for (let j = 0; j < detail.batches.length; j++) {
            const batch = detail.batches[j];

            // 批号校验
            const batchNo = (batch.drugBatchNo || '').trim();
            if (!batchNo) {
              this.$message.closeAll();
              this.$message.error(`商品"${detail.drugName}"的批次${j + 1}缺少批号`);
              return;
            }

            // 生产日期校验
            if (!batch.drugPd) {
              this.$message.closeAll();
              this.$message.error(`商品"${detail.drugName}"的批次${j + 1}缺少生产日期`);
              return;
            }

            // 有效期校验
            if (!batch.drugExp) {
              this.$message.closeAll();
              this.$message.error(`商品"${detail.drugName}"的批次${j + 1}缺少有效期`);
              return;
            }

            // 确认数量校验
            const checkNum = parseFloat(batch.drugCheckNum || batch.drugNum);
            if (!checkNum || checkNum <= 0) {
              this.$message.closeAll();
              this.$message.error(`商品"${detail.drugName}"的批次${j + 1}确认数量必须大于0`);
              return;
            }
          }

          // 检查批次总数量是否与原始数量一致（仅提示，不阻止）
          const totalQty = detail.batches.reduce((sum, b) => sum + (parseFloat(b.drugCheckNum || 0) || 0), 0);
          const originalQty = parseFloat(detail.drugNum);
          if (Math.abs(totalQty - originalQty) > 0.01) {
            this.$message.closeAll();
            this.$message.warning(`商品"${detail.drugName}"的数量不匹配：实际${totalQty} vs 原始${originalQty}，将以部分收货方式处理`);
            // 不 return，允许继续提交
          }
        }

        // 校验通过，组装提交数据
        const detailList = [];
        this.currentBillDetails.forEach(detail => {
          detail.batches.forEach(batch => {
            detailList.push({
              billsId: this.currentBillId,
              drugId: batch.drugId,
              drugName: batch.drugName,
              drugGg: batch.drugGg,
              drugDw: batch.drugDw,
              drugCd: batch.drugCd,
              drugBatchNo: batch.drugBatchNo,
              drugPd: batch.drugPd,
              drugExp: batch.drugExp,
              drugNum: batch.drugNum.toString(),
              drugCheckNum: batch.drugCheckNum,
              parentDetailId: batch.parentDetailId,
            });
          });
        });

        const payload = {
          billsId: this.currentBillId,
          detailList: detailList,
        };

        // 调用接口提交
        this.loading = true;
        receiveGoods(payload)
          .then(res => {
            this.loading = false;
            this.batchDialogVisible = false;
            this.$message.success('收货确认成功');
            this.handleQuery(); // 重新加载表格
          })
          .catch(err => {
            this.loading = false;
            this.$message.error('收货确认失败：' + (err.message || '未知错误'));
          });
      },

      handleCancel(row) {
        this.$prompt('请输入作废原因', '作废', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '作废原因不能为空'
        }).then(({
          value
        }) => {
          cancelBills(row.billsId, value).then(res => {
            this.$message.success('作废成功');
            this.handleQuery();
          }).catch(err => {
            this.$message.error('作废失败：' + (err.response?.data?.msg || err.message));
          })
        })
      },
      rejection(row) {
        this.$prompt('请输入拒收原因', '拒收', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /.+/,
          inputErrorMessage: '拒收原因不能为空'
        }).then(({
                   value
                 }) => {
          rejectGoods(row.billsId, value).then(res => {
            this.$message.success('拒收成功');
            this.handleQuery();
          }).catch(err => {
            this.$message.error('拒收失败：' + (err.response?.data?.msg || err.message));
          })
        })
      },
      resetQuery() {
        this.dateRange = []
        this.queryParams = {
          orderNo: '',
          supplierName: '',
          orderStatus: '-2',
          optType: -1,
          beginTime: null,
          endTime: null
        }
        this.handleQuery();
      },
      handleQuery() {
        this.loading = true;

        // 构建完整的查询参数
        const queryData = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          orderNo: this.queryParams.orderNo,
          supplierName: this.queryParams.supplierName, // 往来单位检索
          beginTime: this.queryParams.beginTime, // 制单开始时间
          endTime: this.queryParams.endTime, // 制单结束时间
          orderStatus: this.queryParams.orderStatus,
          optType: this.queryParams.optType,
          type:'0',
        };

        console.log('发送查询请求，参数:', queryData); // 调试用

        buyStoreList(queryData).then(res => {
          this.headerList = res.rows || [];
          this.total = res.total || 0;
          this.loading = false;
          console.log('查询结果:', res); // 调试用
        }).catch(err => {
          this.loading = false;
          console.error('获取数据失败:', err);
          this.$message.error('获取数据失败: ' + (err.message || '未知错误'));
        });
      },
      handleAdd() {
        this.$router.push({
          path: "/storage/buyStore/qmsDocument",
        });
      },
      handleSizeChange(newPageSize) {
        this.pageSize = newPageSize;
        this.pageNum = 1;
      },
      handleCurrentChange(newPage) {
        this.pageNum = newPage;
      },
    },
  }
</script>
<style scoped>
  .mt20 {
    margin-top: 20px;
  }

  .mb10 {
    margin-bottom: 10px;
  }

  /* 商品信息项样式 */
  .info-item {
    display: flex;
    align-items: center;
    padding: 8px 0;
  }

  .info-label {
    font-weight: 600;
    color: #606266;
    margin-right: 8px;
    min-width: 80px;
  }

  .info-value {
    color: #303133;
    flex: 1;
  }

  /* 批次列表样式 */
  .batch-list {
    margin-top: 15px;
  }

  .batch-item {
    margin-bottom: 15px;
    padding: 15px;
    background-color: #F5F7FA;
    border-radius: 4px;
    border: 1px solid #DCDFE6;
  }

  .batch-item:last-child {
    margin-bottom: 0;
  }

  /* 状态文本样式 */
  .status-text {
    color: #909399;
    font-size: 14px;
  }

  .status-text.success {
    color: #67C23A;
  }

  .status-text.error {
    color: #F56C6C;
  }


  /* 状态文本样式 */
  .status-text {
    color: #909399;
    font-size: 12px;
  }

  .status-text.success {
    color: #67C23A;
  }

  .status-text.error {
    color: #F56C6C;
  }

  /* 表格自适应宽度 */
  .el-table {
    width: 100%;
  }

  .el-table th,
  .el-table td {
    padding: 8px 0;
  }

  /* 表单项间距优化 */
  .el-form-item {
    margin-bottom: 18px;
  }

  /* 按钮组优化 */
  .el-button+.el-button {
    margin-left: 8px;
  }

  /* 日期选择器宽度 */
  .el-date-editor.el-input {
    width: 100%;
  }
</style>
